package com.iot.protocol;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

@Slf4j
public class UdpClient implements AutoCloseable {
    private final String serverHost;
    private final int serverPort;
    private final DatagramSocket socket;

    public UdpClient(String serverHost, int serverPort) throws IOException {
        this.serverHost = serverHost;
        this.serverPort = serverPort;
        this.socket = new DatagramSocket();
        log.info("UDP客户端已初始化，目标服务器: {}:{}", serverHost, serverPort);
    }

    public void sendMessage(String message) throws IOException {
        byte[] sendData = message.getBytes(StandardCharsets.UTF_8);
        InetAddress serverAddress = InetAddress.getByName(serverHost);
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, serverPort);
        
        socket.send(sendPacket);
        log.info("已发送消息: {}", message);
    }

    @Override
    public void close() {
        if (socket != null && !socket.isClosed()) {
            socket.close();
            log.info("UDP客户端已关闭");
        }
    }

    public static void main(String[] args) {
//        if (args.length != 2) {
//            System.out.println("使用方法: java -jar iot-protocol.jar <服务器地址> <服务器端口>");
//            System.exit(1);
//        }

        String serverHost = "192.168.1.12";
        int serverPort = 6001;

//        String serverHost = "127.0.0.1";
//        int serverPort = 8889;

        try (UdpClient client = new UdpClient(serverHost, serverPort);
             Scanner scanner = new Scanner(System.in)) {
            
            System.out.println("UDP客户端已启动，请输入要发送的消息（输入'exit'退出）：");
            
            while (true) {
                String message = scanner.nextLine();
                if ("exit".equalsIgnoreCase(message)) {
                    break;
                }
                client.sendMessage(message);
            }
        } catch (IOException e) {
            log.error("UDP客户端发生错误: {}", e.getMessage(), e);
        }
    }
} 